package com.dys.testjdk9;

import java.io.*;

/**
 * @className: com.dys.testjdk9.TryTest
 * @description: try语法升级
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/09/03 下午11:35
 */
public class TryTest {

    /**
     * 传统写法
     */
    private static void traditionalWriting() {
        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(new FileInputStream("e:/demo1.txt"));
            isr.read();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != isr) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * JAVA 8中已经对try语法进行了升级,可以将要释放的资源放到try后面的小括号中,
     * 这样就不用通过finally语句块释放资源了,**但是要求执行后必须关闭的资源一定要放在try子句中进行初始化,否则编译不通过
     */
    private static void java8Write() {
        // JAVA8 try catch finally语句块
        try (InputStreamReader isr = new InputStreamReader(new FileInputStream("e:/demo1.txt"))) {
            isr.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 因为isr是局部变量，想在外面处理就不可以
    }

    /**
     * JAVA 9 资源的关闭操作,我们可以在try子句中使用已经初始化的资源但是此时的资源必须 是final修饰的,final可以省略不写
     *
     * @throws FileNotFoundException
     */
    private static void java9Write() throws FileNotFoundException {
        // JAVA9 try catch finally语句块
        InputStreamReader isr = new InputStreamReader(new FileInputStream("d:/aaa.txt"));
        OutputStreamWriter isw = new OutputStreamWriter(new FileOutputStream("d:/aaa.txt"));
        try (isr; isw) {
            isr.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
